package com.qf.mvc2203.controller;

import com.qf.mvc2203.ex.UserException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.sql.SQLException;

/**
 * 演示异常处理
 */
@Controller
@RequestMapping("/ex")
public class ExController {

    /**
     * 演示自己写代码处理异常
     * @return
     */
    @RequestMapping("/test1")
    public String test1(){

        System.out.println("ExController test1...");

        try {
            int a = 1/0;
        }catch (Exception e){
            e.printStackTrace();
            // 返回自定义的错误页面
            return "/error/error01.html";
        }


        return "/hi.html";

    }


    /**
     * 测试抛出自定义异常
     * @return
     */
    @RequestMapping("/test2")
    public String test2(){

        System.out.println("ExController test2...");


        try {
            // 业务代码

            throw new UserException("001","用户名重复了");

        }
        catch (UserException e){
            System.out.println(e.getMessage());
            System.out.println(e.getCode());
            System.out.println(e.getMsg());

            // 返回用户模块对应的自定义错误页面
            return "/error/error02.html";

        }
        catch (Exception e){
            return "/error/error01.html";
        }

    }

    /**
     * 测试统一异常处理器能否捕获并处理异常
     * 运行时异常
     * @return
     */
    @RequestMapping("/test3")
    public String test3(){
        System.out.println("ExController test3...");
        throw new UserException("001","用户名重复了");
    }

    /**
     * 测试统一异常处理器能否捕获并处理异常
     * 非运行时异常，直接抛出
     * @return
     */
    @RequestMapping("/test4")
    public String test4() throws SQLException {
        System.out.println("ExController test4...");
        if(false){
             throw new SQLException();
        }
        return "/hi.html";
    }


    /**
     * 测试统一异常处理器能否捕获并处理异常
     * 异常类型转换
     * @return
     */
    @RequestMapping("/test5")
    public String test5() {
        System.out.println("ExController test4...");
        try {
            throw new SQLException();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new UserException("001","用户名重复了");
        }
    }



}
